package com.ruoyi.djb.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.annotation.PassToken;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.annotation.UserLoginToken;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.common.utils.jwtUtils;
import com.ruoyi.djb.domain.*;
import com.ruoyi.djb.mapper.*;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.*;

import static com.ruoyi.common.utils.DateUtils.YYYY_MM_DD_HH_MM_SS;
import static com.ruoyi.djb.config.Constants.*;

@Controller
@RequestMapping("user")
public class UserController extends BaseController {
    private static final String AlgorithmValue="jsdfsdfDFDfsd2343dfFDF";
    @Resource
    private DjbUserMapper userMapper;
    @Resource
    private DjbDistrictUserMapper districtUserMapper;
    @Resource
    private DjbDistrictMapper districtMapper;
    @Resource
    private DjbGateMapper gateMapper;
    @Resource
    private DjbBuildingMapper buildingMapper;
    @Resource
    private DjbRegistryMapper registryMapper;
    @Resource
    private DjbShareInfoMapper shareInfoMapper;
    @Resource
    private DjbReleaseMapper releaseMapper;
    @Resource
    private DjbAdminMapper adminMapper;
    @Resource
    private DjbUserRemindMapper remindMapper;
    @Resource
    private DjbRegHisMapper regHisMapper;
    @Resource
    private DjbReasonMapper reasonMapper;
    @Resource
    private DjbExamMapper examMapper;
    @Resource
    private DjbTagMapper tagMapper;
    @Resource
    private DjbUserLimitMapper userLimitMapper;
    @Resource
    private DjbDistrictBluetoothMapper bluetoothMapper;

    @Value("${djb.env}")
    private String env;

    /*小程序登录* */
    @PostMapping("/Login")
    @ResponseBody
    @PassToken
    public AjaxResult userLogin(String code){
        String sendGet = HttpUtils.sendGet("https://api.weixin.qq.com/sns/jscode2session", "appid=wx023fe513b09669b7&secret=5584582f2847ae22da3d85534ed31541&js_code="+code+"&grant_type=authorization_code");
        JSONObject res = JSONObject.parseObject(sendGet);
        if(!res.containsKey("openid")){
            return error(res.getString("errmsg"));
        }
        String openId = res.getString("openid");
        DjbUser djbUser = userMapper.selectDjbUserByOpenId(openId);
        if(djbUser==null){
            /*注册新用户*/
            djbUser = new DjbUser();
            djbUser.setName("");
            djbUser.setCreateTime(DateUtils.getNowDate());
            djbUser.setOpenId(openId);
            djbUser.setMobile("");
            djbUser.setUnionId(res.getString("unionid"));
            djbUser.setToken("token");
            djbUser.setHead("");
            userMapper.insertDjbUser(djbUser);
        }else if(djbUser.getUnionId().isEmpty()){
            djbUser.setUnionId(res.getString("unionid"));
            userMapper.updateDjbUser(djbUser);
        }
        Map<String,Object> params = new HashMap<>();
        params.put("id",djbUser.getId());
        String token = jwtUtils.getToken(params);
        djbUser.setToken(token);
        userMapper.updateDjbUser(djbUser);
        Map<String,Object> ret = new HashMap<>();
        ret.put("token",djbUser.getToken());
        ret.put("id",djbUser.getId());
        ret.put("user", djbUser);
        /*查询用户认证的小区*/
        DjbDistrictUser query = new DjbDistrictUser();
        query.setUserId(djbUser.getId());
        List<DjbDistrictUser> djbDistrictUsers = districtUserMapper.selectDjbDistrictUserList(query);
        ret.put("districtList",djbDistrictUsers);
        return success(ret);
    }

    /*认证的小区列表 包括各种状态* */
    @GetMapping("/userDistrictList")
    @ResponseBody
    @UserLoginToken
    public AjaxResult userDistrictList(HttpServletRequest request){
        DjbUser user = (DjbUser) request.getAttribute("user");
        /*查询用户认证的小区*/
        DjbDistrictUser query = new DjbDistrictUser();
        query.setUserId(user.getId());
        List<DjbDistrictUser> djbDistrictUsers = districtUserMapper.selectDjbDistrictUserList(query);
        if(djbDistrictUsers.isEmpty()){
            return AjaxResult.warn("无认证的小区");
        }
        Map<String,Object> ret = new HashMap<>();
        ret.put("districtList",djbDistrictUsers);
        return success(ret);
    }

    /*获取用户手机号* */
    @GetMapping("/getUserPhone")
    @ResponseBody
    @UserLoginToken
    public AjaxResult getUserPhone(HttpServletRequest request,String code) throws Exception {
        DjbUser user = (DjbUser) request.getAttribute("user");
        String token=getAccessToken();
        if(token==null){
            return error("获取accessToken失败");
        }
        String postUrl = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + token;
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", code); // openid
        String s = HttpUtils.httpPostJson(postUrl, jsonObject);
        JSONObject ret = JSONObject.parseObject(s);
        if(ret.getIntValue("errcode")==0){
            String phone = ret.getJSONObject("phone_info").getString("purePhoneNumber");
            user.setMobile(phone);
            userMapper.updateDjbUser(user);
            JSONObject ret2 = new JSONObject();
            ret2.put("phone",phone);
            return success(ret2);
        }else{
            return error(ret.getString("errmsg"));
        }
    }

    /*小区列表* */
    @GetMapping("/districtList")
    @ResponseBody
    @UserLoginToken
    public AjaxResult districtList(HttpServletRequest request,String longitude,String latitude){
        DjbUser user = (DjbUser) request.getAttribute("user");
        List<DjbDistrict> djbDistricts = districtMapper.selectDjbDistrictList(new DjbDistrict());
        for(DjbDistrict tmp : djbDistricts){
            double distance = getDistance(Double.parseDouble(tmp.getLongitude()), Double.parseDouble(tmp.getLatitude()), Double.parseDouble(longitude), Double.parseDouble(latitude));
            tmp.setDistance((int) distance);
        }
        djbDistricts.sort((o1, o2) -> {
            Integer name1 = o1.getDistance();//name1是从你list里面拿出来的一个
            Integer name2 = o2.getDistance();//name1是从你list里面拿出来的一个
            return name2.compareTo(name1);
        });
        Map<String,Object> ret = new HashMap<>();
        ret.put("districtList",djbDistricts);
        return success(ret);
    }

    /*小区详情* */
    @GetMapping("/districtDetail")
    @ResponseBody
    @UserLoginToken
    public AjaxResult districtDetail(HttpServletRequest request, Integer districtId){
        DjbUser user = (DjbUser) request.getAttribute("user");
        DjbDistrict djbDistrict = districtMapper.selectDjbDistrictById(districtId);
        if(djbDistrict==null){
            return error("该机构已解散");
        }
        DjbGate query = new DjbGate();
        query.setDistrictId(districtId);
        List<DjbGate> djbGates = gateMapper.selectDjbGateList(query);
        Map<String,Object> ret = new HashMap<>();
        ret.put("gateList",djbGates);
        DjbBuilding query2 = new DjbBuilding();
        query2.setDistrictId(districtId);
        List<DjbBuilding> djbBuildings = buildingMapper.selectDjbBuildingList(query2);
        if(djbDistrict.getType()==BUILDING_TYPE_DEPARTMENT){
            djbBuildings.sort((o1, o2) -> {
                Integer name1 = o1.getVisit();//name1是从你list里面拿出来的一个
                Integer name2 = o2.getVisit();//name1是从你list里面拿出来的一个
                return name2.compareTo(name1);
            });
        }
        ret.put("buildingList",djbBuildings);
//        String reasons = djbDistrict.getReasons();
//        JSONObject jsonObject = JSONObject.parseObject(reasons, Feature.OrderedField);
//        JSONObject jsonObject2= new JSONObject();
//        Set<Map.Entry<String, Object>> entries = jsonObject.entrySet();
//        for(Map.Entry<String, Object> map : entries){
//            if((int)map.getValue()==1){
//                jsonObject2.put(map.getKey(),map.getValue());
//            }
//        }
//        djbDistrict.setReasons(jsonObject2.toJSONString());
        DjbUserLimit userLimit = new DjbUserLimit();
        userLimit.setDistrictId(districtId);
        userLimit.setUserId(user.getId());
        List<DjbUserLimit> djbUserLimits = userLimitMapper.selectDjbUserLimitList(userLimit);
        if(djbUserLimits.isEmpty()){
            djbDistrict.setIsLimit(0);
        }else{
            djbDistrict.setIsLimit(1);
        }
        ret.put("district",djbDistrict);
        return success(ret);
    }

    /*门岗详情* */
    @GetMapping("/gateDetail")
    @ResponseBody
    @PassToken
    public AjaxResult gateDetail(HttpServletRequest request,Integer gateId){
        DjbUser user = (DjbUser) request.getAttribute("user");
        DjbGate djbGate = gateMapper.selectDjbGateById(gateId);
        Map<String,Object> ret = new HashMap<>();
        ret.put("gateDetail",djbGate);
        return success(ret);
    }

    /*登记新增* */
    @PutMapping("/registryAdd")
    @ResponseBody
    @UserLoginToken
    @RepeatSubmit
    public AjaxResult registryAdd(HttpServletRequest request,
                                  String name,Integer shareId,String mobile,String address,
                                  Integer districtId,Integer gateId,String reason,String type,
                                  Integer createType,Integer userType,Integer building,Integer unit,Integer floor,Integer room,
                                  String department,String remark,String idNumber,Integer regType,String visitPerson,Integer visitPersonId){
        DjbUser user = (DjbUser) request.getAttribute("user");
        Date nowDate = DateUtils.getNowDate();
        DjbShareInfo djbShareInfo;
        int shareFromId=0;
        if(shareId != null){
            djbShareInfo = shareInfoMapper.selectDjbShareInfoById(shareId);
            if(djbShareInfo==null){
                return error("分享ID错误");
            }
            if(djbShareInfo.getVisitId()!=null){
                return error("该链接已登记过，请勿重复登记");
            }
            if(DateUtils.differentBySecond(djbShareInfo.getCreateTime(),nowDate)>600){
                return error("该链接已超时");
            }
            shareFromId=djbShareInfo.getUserId();
        }
        /*且近10分钟只能提交5次（仅包含访客登记和住户登记）超过则文字提示  操作频繁*/
        DjbRegHis djbRegHis = new DjbRegHis();
        djbRegHis.setUserId(user.getId());
        List<DjbRegHis> djbRegHis1 = regHisMapper.selectDjbRegHisListTenMin(djbRegHis);
        if(djbRegHis1.size()>=5){
            AjaxResult ajaxResult = new AjaxResult();
            ajaxResult.put("code",701);
            ajaxResult.put("msg","操作频繁");
            return ajaxResult;
        }
        djbRegHis.setRegType("");
        djbRegHis.setCreateTime(nowDate);
        regHisMapper.insertDjbRegHis(djbRegHis);
        DjbDistrict djbDistrict = districtMapper.selectDjbDistrictById(districtId);
        /*如果放行的是车辆，且小区开了最大车辆限制,则车辆数加1*/
        if(userType==1){
            if(djbDistrict.getMaxCar()!=0 && djbDistrict.getCurrentCar()>=djbDistrict.getMaxCar()){
                AjaxResult ajaxResult = new AjaxResult();
                ajaxResult.put("code",702);
                ajaxResult.put("msg","场内访客车辆已超限");
                return ajaxResult;
            }
        }
        /*新增同一行人（车辆）来访次数月度限制*/
        if(userType==USER_TYPE_PERSON  && djbDistrict.getUserMaxMonth()!=0){
            DjbRelease check = new DjbRelease();
            check.setMobile(mobile);
            check.setDistrictId(districtId);
            Map<String, Object> params= new HashMap<>();
            params.put("beginTime", DateFormatUtils.format(DateUtils.getMonthBegin(),YYYY_MM_DD_HH_MM_SS));
            check.setParams(params);
            List<DjbRelease> djbReleaseList = releaseMapper.selectDjbReleaseList(check);
            if(djbReleaseList.size()>=djbDistrict.getUserMaxMonth()){
                AjaxResult ajaxResult = new AjaxResult();
                ajaxResult.put("code",703);
                ajaxResult.put("msg","本月登记次数已超限");
                ajaxResult.put("maxMonth",djbDistrict.getUserMaxMonth());
                return ajaxResult;
            }
        }
        /*新增同一行人（车辆）来访次数月度限制*/
        if(userType==USER_TYPE_CAR  && djbDistrict.getCarMaxMonth()!=0){
            DjbRelease check = new DjbRelease();
            check.setName(name);
            check.setDistrictId(districtId);
            Map<String, Object> params= new HashMap<>();
            Date monthBegin = DateUtils.getMonthBegin();
            params.put("beginTime",DateFormatUtils.format(DateUtils.getMonthBegin(),YYYY_MM_DD_HH_MM_SS));
            check.setParams(params);
            List<DjbRelease> djbReleaseList = releaseMapper.selectDjbReleaseList(check);
            if(djbReleaseList.size()>=djbDistrict.getCarMaxMonth()){
                AjaxResult ajaxResult = new AjaxResult();
                ajaxResult.put("code",703);
                ajaxResult.put("msg","本月登记次数已超限");
                ajaxResult.put("maxMonth",djbDistrict.getCarMaxMonth());
                return ajaxResult;
            }
        }
        DjbRegistry check2 = new DjbRegistry();
        check2.setUserType(userType);
        if(userType==USER_TYPE_PERSON){
            check2.setMobile(mobile);
        }else{
            check2.setName(name);
        }
        check2.setExamFlag("审核");
        check2.setDistrictId(districtId);
        List<DjbRegistry> djbRegistries2 = registryMapper.selectDjbRegistryList(check2);
        if(createType.equals(CREATE_TYPE_VISITOR)&&gateId!=null){
            for(DjbRegistry  tmp : djbRegistries2){
                if(tmp.getGateId()==0|| tmp.getGateId().equals(gateId)){
                    //判断条件，如果存在内部登记或者同一个门岗的登记，则返回错误。
                    JSONObject ret = new JSONObject();
                    ret.put("id",djbRegistries2.get(0).getId());
                    return AjaxResult.error("该访客信息已登记",ret);
                }
            }
        }else{
            if(!djbRegistries2.isEmpty()){
                JSONObject ret = new JSONObject();
                ret.put("id",djbRegistries2.get(0).getId());
                return AjaxResult.error("该访客信息已登记",ret);
            }
        }

        if(userType==USER_TYPE_PERSON&&djbDistrict.getVipCheckId()==SYS_YES&&djbDistrict.getBalance()>10&&djbDistrict.getIdNumberSwitch()==SYS_YES&&idNumber!=null&&!idNumber.isEmpty()){
            boolean b = checkNameAndIdNumber(name, idNumber,djbDistrict);
            if(!b){
                return error("身份信息校验不符！");
            }
        }

        int status = SYS_NO;
        int statusUser = SYS_NO;
        List<DjbUser> examUser = new ArrayList<>();
        List<DjbUser> examUserNew = new ArrayList<>();//添加到审核的用户，区分与examUser，不考虑用户的微信OPENID是否为空
        List<DjbAdmin> examAdmin = new ArrayList<>();
        /*开启人工审核后访客登记需要审核（户主）成功后门岗处才可放行*/
        Integer manualReview = djbDistrict.getManualReview();
        Integer manualReviewUser = djbDistrict.getManualReviewUser();
        //判断登记类型是不是小区，且登记人是业主,且住户登记开启
        if(djbDistrict.getType()==BUILDING_TYPE_BUILD&&createType.equals(CREATE_TYPE_USER)&&manualReviewUser.equals(SYS_YES)){
            Integer conditions = djbDistrict.getConditionsUser();
            if(conditions==4||conditions.equals(userType)){//判断审核条件是不是车和人或者登记类型与设置的人或者相符
                /*解除审核状态和关注公众号的关联*/
                statusUser=SYS_EXAM;
                //开启人工审核后住户登记需要审核（管家）成功后门岗处才可放行
                if(building!=null&&unit!=null&&floor!=null&&room!=null){
                    //找管家
                    DjbBuilding djbBuilding = buildingMapper.selectDjbBuildingById(building);
                    String keeper = djbBuilding.getKeeper();
                    if(!keeper.isEmpty()){
                        JSONArray array = JSONArray.parseArray(keeper);
                        for(Object tmp : array){
                            JSONObject keep= (JSONObject)tmp;
                            String keep_id = keep.getString("id");
                            DjbAdmin admin = adminMapper.selectDjbAdminById(Integer.parseInt(keep_id));
                            if(admin.getIsPost()==SYS_YES){
                                examAdmin.add(admin);
                                break;
                            }
                        }
                    }
                    if(examAdmin.isEmpty()){
                        /*未绑定管家或者管家都不在岗 找客服主管*/
                        DjbAdmin admin = new DjbAdmin();
                        admin.setDistrictId(districtId);
                        admin.setType(ADMIN_TYPE_MANAGER_WUYE);
                        List<DjbAdmin> djbAdmins = adminMapper.selectDjbAdminList(admin);
                        for(DjbAdmin tmp : djbAdmins){
                            if(tmp.getIsPost()==SYS_YES){
                                examAdmin.add(tmp);
                            }
                        }
                    }
                    if(examAdmin.isEmpty()&&djbDistrict.getNightScene()==SYS_YES){
                        /*未绑定管家或者管家 服务主管都不在岗,且开启夜间模式*/
                        if(djbDistrict.getConditionsNightScene()==4||djbDistrict.getConditionsNightScene().equals(userType)){
                            statusUser = SYS_NO;
                        }
                        type="夜间场景";
                    }
                }
            }
        }else if(createType.equals(CREATE_TYPE_VISITOR)){
            //当访客登记
            if(manualReview.equals(SYS_YES)){
                Integer conditions = djbDistrict.getConditons();
                if(conditions==4||conditions.equals(userType)){
                    /*解除审核状态和关注公众号的关联*/
                    status=SYS_EXAM;
                    //当访客登记，物业登记，门卫登记访客信息，访客来访门卫放行后，只有该户户主能收到访客来访通知
                    if(djbDistrict.getType()==BUILDING_TYPE_BUILD){
                        /*有拜访人 拜访人接受*/
                        if(visitPerson!=null && !visitPerson.isEmpty() && visitPersonId!=null){
                            DjbUser djbUser = userMapper.selectDjbUserById(visitPersonId);
                            if(djbUser!=null&&djbUser.getOpenId2()!=null&&!djbUser.getOpenId2().isEmpty()){
                                examUser.add(djbUser);
                            }
                            examUserNew.add(djbUser);
                        }else if(building!=null&&unit!=null&&floor!=null&&room!=null){
                            //无拜访人，找业主
                            DjbDistrictUser districtUser = new DjbDistrictUser();
                            districtUser.setDistrictId(districtId);
                            districtUser.setBuilding(building);
                            districtUser.setUnit(unit);
                            districtUser.setFloor(floor);
                            districtUser.setRoom(room);
                            List<DjbDistrictUser> djbDistrictUsers = districtUserMapper.selectDjbDistrictUserList(districtUser);
                            for(DjbDistrictUser tmp: djbDistrictUsers){
                                if(tmp.getType().equals(0)||tmp.getStatus()!=SYS_STATUS_PASS) continue;
                                DjbUser djbUser = userMapper.selectDjbUserById(tmp.getUserId());
                                if(djbUser!=null&&djbUser.getOpenId2()!=null&&!djbUser.getOpenId2().isEmpty()){
                                    examUser.add(djbUser);
                                }
                                examUserNew.add(djbUser);
                            }
                        }
                    }else if(djbDistrict.getType()==BUILDING_TYPE_DEPARTMENT||djbDistrict.getType()==BUILDING_TYPE_COMPANY){
                        /*有拜访人 拜访人接受*/
                        if(visitPerson!=null && !visitPerson.isEmpty() && visitPersonId!=null){
                            DjbUser djbUser = userMapper.selectDjbUserById(visitPersonId);
                            if(djbUser!=null&&djbUser.getOpenId2()!=null&&!djbUser.getOpenId2().isEmpty()){
                                examUser.add(djbUser);
                            }
                            examUserNew.add(djbUser);
                        }else{
                            //无拜访人，找部门主管或者公司前台
                            DjbDistrictUser districtUser = new DjbDistrictUser();
                            districtUser.setDistrictId(districtId);
                            districtUser.setBuilding(building);
                            List<DjbDistrictUser> djbDistrictUsers = districtUserMapper.selectDjbDistrictUserList(districtUser);
                            for(DjbDistrictUser tmp: djbDistrictUsers){
                                if(tmp.getType().equals(0)||tmp.getStatus()!=SYS_STATUS_PASS) continue;
                                DjbUser djbUser = userMapper.selectDjbUserById(tmp.getUserId());
                                if(djbUser!=null&&djbUser.getOpenId2()!=null&&!djbUser.getOpenId2().isEmpty()){
                                    examUser.add(djbUser);
                                }
                                examUserNew.add(djbUser);
                            }
                        }
                    }
                }
            }
        }
        DjbRegistry registry = new DjbRegistry();
        registry.setUserId(shareFromId==0?user.getId():shareFromId);
        if(shareId!=null && shareId!=0){
            registry.setInputId(user.getId());
        }
        registry.setName(name);
        registry.setMobile(mobile);
        registry.setAddress(address);
        registry.setDistrictId(districtId);
        registry.setGateId(gateId);
        String gateName="无";
        if(gateId!=null){
            DjbGate gate = gateMapper.selectDjbGateById(gateId);
            if(gate!=null){
                gateName=gate.getName();
            }
        }
        registry.setReason(reason);
        registry.setType(type);
        int s;
        if(createType.equals(CREATE_TYPE_VISITOR)){
            s=status;
        }else{
            s=statusUser;
        }
        DjbDistrictUser districtUser = new DjbDistrictUser();
        districtUser.setUserId(shareFromId==0?user.getId():shareFromId);
        districtUser.setStatus(SYS_STATUS_PASS);
        districtUser.setDistrictId(districtId);
        List<DjbDistrictUser> djbDistrictUsers = districtUserMapper.selectDjbDistrictUserList(districtUser);
        if(!djbDistrictUsers.isEmpty()){
            registry.setCreateName(djbDistrictUsers.get(0).getName());
        }else{
            registry.setCreateName(user.getName());
        }
        registry.setStatus(s);
        registry.setCreateType(createType);
        registry.setUserType(userType);
        registry.setCreateTime(nowDate);
        registry.setBuilding(building);
        registry.setUnit(unit);
        registry.setFloor(floor);
        registry.setRoom(room);
        registry.setDepartment(department);
        registry.setRemark(remark);
        registry.setIdNumber(idNumber);
        registry.setDistrictName(djbDistrict.getName());
        registry.setGateName(gateName);
        registry.setDistrictImage(djbDistrict.getCoverUrl());
        registry.setDistrictPhone(djbDistrict.getMobile());
        registry.setVisitPerson(visitPerson);
        registry.setVisitPersonId(visitPersonId);
        registryMapper.insertDjbRegistry(registry);
        if(shareId != null){
            djbShareInfo = shareInfoMapper.selectDjbShareInfoById(shareId);
            djbShareInfo.setVisitId(user.getId());
            djbShareInfo.setUpdateTime(nowDate);
            shareInfoMapper.updateDjbShareInfo(djbShareInfo);
        }

        if(status==SYS_EXAM){
            for(DjbUser tmp : examUser){
                new Thread(() -> {
                    /*发送消息通知*/
                    sendExamNotice(tmp.getOpenId2(), registry.getName(), registry.getMobile(),registry.getDistrictName()+ registry.getAddress(), registry.getId(),registry.getType(),registry.getReason(),"user",tmp.getId());
                }).start();
            }
            for(DjbUser tmp : examUserNew){
                DjbExam djbExam = new DjbExam();
                djbExam.setUserId(tmp.getId());
                djbExam.setExamType("user");
                djbExam.setRegistryId(registry.getId());
                djbExam.setStatus(0);
                djbExam.setDeleteFlag(0);
                djbExam.setCreateTime(nowDate);
                examMapper.insertDjbExam(djbExam);
            }
        }
        if(statusUser==SYS_EXAM){
            for(DjbAdmin tmp : examAdmin){
                new Thread(() -> {
                    /*发送消息通知*/
                    sendExamNotice(tmp.getOpenId2(), registry.getName(), registry.getMobile(), registry.getDistrictName()+registry.getAddress(), registry.getId(),registry.getType(),registry.getReason(),"admin",tmp.getId());
                }).start();
            }
        }

        /*解除审核状态和关注公众号的关联*/
//        if(!sendExamResult&&(statusUser==SYS_EXAM||status==SYS_EXAM)){
//            registry.setStatus(SYS_NO);
//            registryMapper.updateDjbRegistry(registry);
//        }
        if(department!=null && !department.isEmpty()){
            user.setLastDepartment(department);
        }
        if(remark!=null && !remark.isEmpty()){
            user.setLastRemark(remark);
        }
        if(idNumber!=null && !idNumber.isEmpty()){
            user.setIdNumber(idNumber);
        }
        /*业主登记的不需要记录*/
        if(!createType.equals(CREATE_TYPE_USER)){
            if(userType.equals(USER_TYPE_CAR)){
                user.setLastCar(name);
            }else{
                user.setLastName(name);
            }
            user.setLastPhone(mobile);
        }
        userMapper.updateDjbUser(user);
        int isAutoRelease = 0;
        Map<String,Object> ret = new HashMap<>();
        ret.put("status",s);
        ret.put("registryId",registry.getId());
        if(s==SYS_NO&&registry.getUserType()==USER_TYPE_CAR&&djbDistrict.getAutoReleaseSwitch()==SYS_YES&&regType!=null&&regType==REG_TYPE_SCAN){
            /*车辆自动放行*/
            int remindTime=0;
            if(djbDistrict.getAutoReleaseSwitchTag()==1){
//                DjbTag tag = new DjbTag();
//                tag.setCar(name);
//                List<DjbTag> djbTags = tagMapper.selectDjbTagList(tag);
//                remindTime=djbTags.size();

                DjbRelease release2 = new DjbRelease();
                release2.setName(name);
                release2.setUserType(USER_TYPE_CAR);
                List<DjbRelease> djbReleaseList1 = releaseMapper.selectHalfYearThreeTimeReleaseList(release2);
                for(DjbRelease tmp2: djbReleaseList1){
                    if(!tmp2.getTag().isEmpty()){
                        remindTime++;
                    }
                }
            }
            int visitTime=1;
            if(djbDistrict.getAutoReleaseSwitchFirst()==1){
                DjbRelease release = new DjbRelease();
                release.setName(name);
                release.setDistrictId(districtId);
                List<DjbRelease> djbReleaseList = releaseMapper.selectDjbReleaseList(release);
                visitTime=djbReleaseList.size();
            }
            if(remindTime==0&&visitTime!=0){
                DjbDistrictBluetooth bluetooth = new DjbDistrictBluetooth();
                bluetooth.setDistrictId(districtId);
                List<DjbDistrictBluetooth> djbDistrictBluetooths = bluetoothMapper.selectDjbDistrictBluetoothList(bluetooth);
                if(!djbDistrictBluetooths.isEmpty()){
                    /* 发送推送--自动放行*/
                    DjbAdmin query = new DjbAdmin();
                    query.setType(ADMIN_TYPE_GATE);
                    query.setIsPost(SYS_YES);
                    if(gateId!=null){
                        query.setGateId(gateId);
                    }
                    List<DjbAdmin> djbAdmins = adminMapper.selectDjbAdminList(query);
                    if(!djbAdmins.isEmpty()){
                        List<String> jgIdList = new ArrayList<>();
                        for(DjbAdmin tmp: djbAdmins){
                            if(tmp.getRegistrationId().isEmpty())continue;
                            jgIdList.add(tmp.getRegistrationId());
                        }
                        String jgId = String.join(",",jgIdList);
                        String[] split = jgId.split(",");
                        JSONObject id = new JSONObject();
                        id.put("registration_id",split);
                        JSONObject message = new JSONObject();
                        message.put("msg_content","自动抬杆");
                        JSONObject extra = new JSONObject();
                        extra.put("action","自动抬杆");
                        extra.put("actionType","放行");
                        extra.put("registryId",registry.getId());
                        message.put("extras",extra);
                        JSONObject send = new JSONObject();
                        send.put("platform","all");
                        send.put("audience",id);
                        send.put("message",message);
                        JSONObject options = new JSONObject();
                        options.put("time_to_live", 0);
                        send.put("options",options);
                        System.out.println("推送消息"+send.toJSONString());
                        //        send.put("message",new JSONObject().put("msg_content","到达取货"));
                        HttpClientBuilder builder = HttpClientBuilder.create();
                        CloseableHttpClient client = builder.build();
                        String key ="61d4f2c73d4f9c5e83aa6a19";
                        String secret ="ddf2a8ec8122a15580f76626";
                        String Authorization = Base64.getEncoder().encodeToString((key+":"+secret).getBytes(StandardCharsets.UTF_8));
                        HttpPost post = new HttpPost("https://api.jpush.cn/v3/push");
                        post.addHeader("Content-Type", "application/json;charset=utf-8");
                        post.addHeader("Authorization","Basic "+Authorization);
                        ContentType contentType = ContentType.create("application/json","UTF-8");
                        // 设置请求的的参数，requestBody
                        StringEntity str = new StringEntity(send.toString(),contentType);
                        post.setEntity(str);
                        HttpResponse response = null;
                        try {
                            response = client.execute(post);
                            String s1 = EntityUtils.toString(response.getEntity(), "utf-8");
                            System.out.println("极光推送回执"+s1);
                            client.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }else{
                        AjaxResult ajaxResult = releaseRegistry(registry.getId());
                        if((int)ajaxResult.get("code")==0){
                            isAutoRelease=1;
                        }else{
                            System.out.println("自动放行失败："+ajaxResult.get("msg"));
                        }
                    }
                }else{
                    AjaxResult ajaxResult = releaseRegistry(registry.getId());
                    if((int)ajaxResult.get("code")==0){
                        isAutoRelease=1;
                    }else{
                        System.out.println("自动放行失败："+ajaxResult.get("msg"));
                    }
                }
            }
        }else if(s==SYS_NO&&registry.getUserType()==USER_TYPE_PERSON&&djbDistrict.getAutoReleaseSwitchMan()==SYS_YES&&regType!=null&&regType==REG_TYPE_SCAN){
            /*行人自动放行*/
            int remindTime=0;
            if(djbDistrict.getAutoReleaseSwitchManTag()==1){
//                DjbTag tag = new DjbTag();
//                tag.setMobile(mobile);
//                List<DjbTag> djbTags = tagMapper.selectDjbTagList(tag);
//                remindTime=djbTags.size();

                DjbRelease release2 = new DjbRelease();
                release2.setMobile(mobile);
                release2.setUserType(USER_TYPE_PERSON);
                List<DjbRelease> djbReleaseList1 = releaseMapper.selectHalfYearThreeTimeReleaseList(release2);
                for(DjbRelease tmp2: djbReleaseList1){
                    if(!tmp2.getTag().isEmpty()){
                        remindTime++;
                    }
                }
            }
            int visitTime=1;
            if(djbDistrict.getAutoReleaseSwitchManFirst()==1){
                DjbRelease release = new DjbRelease();
                release.setMobile(mobile);
                release.setDistrictId(districtId);
                List<DjbRelease> djbReleaseList = releaseMapper.selectDjbReleaseList(release);
                visitTime=djbReleaseList.size();
            }
            if(remindTime==0&&visitTime!=0){
                /* 自动放行*/
                AjaxResult ajaxResult = releaseRegistry(registry.getId());
                if((int)ajaxResult.get("code")==0){
                    isAutoRelease=1;
                }else{
                    System.out.println("自动放行失败："+ajaxResult.get("msg"));
                }
            }
        }
        ret.put("isAutoRelease",isAutoRelease);
        if(djbDistrict.getType()==BUILDING_TYPE_DEPARTMENT && building!=null&& building!=0){
            DjbBuilding djbBuilding = buildingMapper.selectDjbBuildingById(building);
            djbBuilding.setVisit(djbBuilding.getVisit()+1);
            buildingMapper.updateDjbBuilding(djbBuilding);
        }
        if((regType!=null && regType==1 && djbDistrict.getRegSwitchUserScan()==1 && djbDistrict.getRegSwitchUserScanVoice()==1)||
                (regType!=null && regType==2 && djbDistrict.getRegSwitchUserRemote()==1 && djbDistrict.getRegSwitchUserRemoteVoice()==1)){
            /* 发送推送--声音提醒*/
            DjbAdmin query = new DjbAdmin();
            query.setType(ADMIN_TYPE_GATE);
            query.setIsPost(SYS_YES);
            if(gateId!=null){
                query.setGateId(gateId);
            }
            List<DjbAdmin> djbAdmins = adminMapper.selectDjbAdminList(query);
            if(!djbAdmins.isEmpty()){
                List<String> jgIdList = new ArrayList<>();
                for(DjbAdmin tmp: djbAdmins){
                    if(tmp.getRegistrationId().isEmpty())continue;
                    jgIdList.add(tmp.getRegistrationId());
                }
                String jgId = String.join(",",jgIdList);
                String[] split = jgId.split(",");
                JSONObject id = new JSONObject();
                id.put("registration_id",split);
                JSONObject message = new JSONObject();
                message.put("msg_content","登记成功");
                JSONObject extra = new JSONObject();
                extra.put("action","声音提醒");
                extra.put("actionType","声音");
                extra.put("content",registry.getName());
                message.put("extras",extra);
                JSONObject send = new JSONObject();
                send.put("platform","all");
                send.put("audience",id);
                send.put("message",message);
                JSONObject options = new JSONObject();
                options.put("time_to_live", 0);
                send.put("options",options);
                System.out.println("推送消息"+send.toJSONString());
                //        send.put("message",new JSONObject().put("msg_content","到达取货"));
                HttpClientBuilder builder = HttpClientBuilder.create();
                CloseableHttpClient client = builder.build();
                String key ="61d4f2c73d4f9c5e83aa6a19";
                String secret ="ddf2a8ec8122a15580f76626";
                String Authorization = Base64.getEncoder().encodeToString((key+":"+secret).getBytes(StandardCharsets.UTF_8));
                HttpPost post = new HttpPost("https://api.jpush.cn/v3/push");
                post.addHeader("Content-Type", "application/json;charset=utf-8");
                post.addHeader("Authorization","Basic "+Authorization);
                ContentType contentType = ContentType.create("application/json","UTF-8");
                // 设置请求的的参数，requestBody
                StringEntity str = new StringEntity(send.toString(),contentType);
                post.setEntity(str);
                HttpResponse response = null;
                try {
                    response = client.execute(post);
                    String s1 = EntityUtils.toString(response.getEntity(), "utf-8");
                    System.out.println("极光推送声音提醒回执"+s1);
                    client.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return success(ret);
    }

    /*自动放行*/
    private AjaxResult releaseRegistry(Integer id){
        DjbRegistry registry = registryMapper.selectDjbRegistryById(id);
        if(registry==null){
            return error("记录不存在");
        }
        if(registry.getStatus().equals(SYS_STATUS_PASS)){
            return error("该登记已放行");
        }
        if(registry.getStatus().equals(SYS_STATUS_EXPIRE)){
            return error("该登记已过期");
        }
        if(registry.getStatus().equals(SYS_STATUS_WASTE)){
            return error("该登记已作废");
        }
        if(registry.getStatus().equals(SYS_STATUS_WRONG)){
            return error("该登记已纠错");
        }
        if(registry.getStatus().equals(SYS_STATUS_REBUT)){
            return error("该登记已驳回");
        }
        if(registry.getType().equals(TYPE_TOMORROW_ONE)||registry.getType().equals(TYPE_TOMORROW_WHOLE)){
            return error("该登记属于明日，请刷新重试");
        }
        if(registry.getType().equals(TYPE_TODAY_ONE)||registry.getType().equals("夜间场景")){
            registry.setStatus(SYS_YES);
        }
        registry.setReleaseId(null);
        registry.setReleaseName("自动");
        registry.setReleaseTime(DateUtils.getNowDate());
        registryMapper.updateDjbRegistry(registry);
        /*创建放行记录*/
        DjbRelease release = new DjbRelease();
        release.setUserId(registry.getUserId());
        release.setName(registry.getName());
        release.setMobile(registry.getMobile());
        release.setDistrictId(registry.getDistrictId());
        release.setGateId(registry.getGateId());
//        if(registry.getGateId()==0&&admin.getType().equals(ADMIN_TYPE_GATE)&&admin.getGateId()!=null){
//            release.setGateId(admin.getGateId());
//        }
        release.setAddress(registry.getAddress());
        release.setReason(registry.getReason());
        release.setType(registry.getType());
        release.setReleaseId(registry.getReleaseId());
        release.setReleaseName(registry.getReleaseName());
        release.setReleaseTime(registry.getReleaseTime());
        release.setStatus(SYS_YES);
        release.setCreateType(registry.getCreateType());
        release.setCreateName(registry.getCreateName());
        release.setCreateTime(registry.getCreateTime());
        release.setCreateBy(registry.getCreateBy());
        release.setUserType(registry.getUserType());
        release.setBuilding(registry.getBuilding());
        release.setUnit(registry.getUnit());
        release.setFloor(registry.getFloor());
        release.setRoom(registry.getRoom());
        release.setTag("");
        release.setExamName(registry.getExamName());
        DjbRelease release2 = new DjbRelease();
        if(registry.getUserType()==USER_TYPE_PERSON){
            release2.setMobile(registry.getMobile());
        }else{
            release2.setName(registry.getName());
        }
        release2.setDistrictId(registry.getDistrictId());
        List<DjbRelease> djbReleases = releaseMapper.selectDjbReleaseList(release2);
        release.setVisitNum(djbReleases.size()+1);
        release.setRegId(registry.getId());
        release.setDepartment(registry.getDepartment());
        release.setRemark(registry.getRemark());
        release.setIdNumber(registry.getIdNumber());
        release.setDistrictName(registry.getDistrictName());
        release.setVisitPerson(registry.getVisitPerson());
        release.setVisitPersonId(registry.getVisitPersonId());
        releaseMapper.insertDjbRelease(release);
        /*如果放行的是车辆，且小区开了最大车辆限制,则车辆数加1*/
        DjbDistrict djbDistrict = districtMapper.selectDjbDistrictById(registry.getDistrictId());
        if(registry.getUserType()==1){
            if(djbDistrict.getMaxCar()!=0){
                djbDistrict.setCurrentCar(djbDistrict.getCurrentCar()+1);
                districtMapper.updateDjbDistrict(djbDistrict);
            }
            /*发送入场通知*/
            if(djbDistrict.getVipIncomeSms()==SYS_YES){
                sendIncomeSMS(release.getMobile(),release.getName(),release.getAddress(),djbDistrict.getVipIncomeSmsId(),djbDistrict);
            }
        }
        new Thread(() -> {
            /*发送消息通知*/
            if(registry.getCreateType().equals(CREATE_TYPE_USER)){
                //住户登记访客信息，访客来访门卫放行后，该住户会收到访客来访通知
                Integer userId = registry.getUserId();
                DjbUser djbUser = userMapper.selectDjbUserById(userId);
                if(djbUser!=null&&djbUser.getOpenId2()!=null&&!djbUser.getOpenId2().isEmpty()){
                    sendVisitArrived(djbUser.getOpenId2(),registry.getName(),registry.getMobile(),registry.getAddress(),registry.getReason(),registry.getType());
                }
            }else{//当访客登记，物业登记，门卫登记访客信息，访客来访门卫放行后，只有该户户主能收到访客来访通知
                if(registry.getVisitPerson()!=null && !registry.getVisitPerson().isEmpty() && registry.getVisitPersonId()!=null){
                    DjbUser djbUser = userMapper.selectDjbUserById(registry.getVisitPersonId());
                    if(djbUser!=null&&djbUser.getOpenId2()!=null&&!djbUser.getOpenId2().isEmpty()){
                        sendVisitArrived(djbUser.getOpenId2(),registry.getName(),registry.getMobile(),registry.getAddress(),registry.getReason(),registry.getType());
                    }
                }else{
                    //找业主
                    Integer building = registry.getBuilding();
                    DjbDistrictUser districtUser = new DjbDistrictUser();
                    districtUser.setDistrictId(registry.getDistrictId());
                    if(djbDistrict.getType()==BUILDING_TYPE_BUILD){
                        Integer unit = registry.getUnit();
                        Integer floor = registry.getFloor();
                        Integer room = registry.getRoom();
                        if(building!=null&&unit!=null&&floor!=null&&room!=null){
                            //找业主
                            districtUser.setBuilding(building);
                            districtUser.setUnit(unit);
                            districtUser.setFloor(floor);
                            districtUser.setRoom(room);
                            List<DjbDistrictUser> djbDistrictUsers = districtUserMapper.selectDjbDistrictUserList(districtUser);
                            for(DjbDistrictUser tmp: djbDistrictUsers){
                                if(tmp.getType().equals(0)||tmp.getStatus().equals(SYS_STATUS_TODO)) continue;
                                DjbUser djbUser = userMapper.selectDjbUserById(tmp.getUserId());
                                if(djbUser!=null&&djbUser.getOpenId2()!=null&&!djbUser.getOpenId2().isEmpty()){
                                    sendVisitArrived(djbUser.getOpenId2(),registry.getName(),registry.getMobile(),registry.getAddress(),registry.getReason(),registry.getType());
                                }
                            }
                        }
                    }else if(djbDistrict.getType()==BUILDING_TYPE_DEPARTMENT||djbDistrict.getType()==BUILDING_TYPE_COMPANY){
                        if(building!=null){
                            //找部门主管或前台
                            districtUser.setBuilding(building);
                            List<DjbDistrictUser> djbDistrictUsers = districtUserMapper.selectDjbDistrictUserList(districtUser);
                            for(DjbDistrictUser tmp: djbDistrictUsers){
                                if(tmp.getType().equals(0)||tmp.getStatus().equals(SYS_STATUS_TODO)) continue;
                                DjbUser djbUser = userMapper.selectDjbUserById(tmp.getUserId());
                                if(djbUser!=null&&djbUser.getOpenId2()!=null&&!djbUser.getOpenId2().isEmpty()){
                                    sendVisitArrived(djbUser.getOpenId2(),registry.getName(),registry.getMobile(),registry.getAddress(),registry.getReason(),registry.getType());
                                }
                            }
                        }
                    }
                }
            }
        }).start();
        return success();
    }

    /*小区住户、公司用户、部门用户认证新增* */
    @PutMapping("/VerifyAdd")
    @ResponseBody
    @UserLoginToken
    public AjaxResult userVerifyAdd(HttpServletRequest request,Integer type, Integer districtId,Integer building,Integer unit,Integer floor,Integer room, String mobile, String name){
        DjbUser user = (DjbUser) request.getAttribute("user");
        DjbDistrictUser check = new DjbDistrictUser();
        check.setDistrictId(districtId);
        check.setUserId(user.getId());
        List<DjbDistrictUser> djbDistrictUsers = districtUserMapper.selectDjbDistrictUserList(check);
        if(!djbDistrictUsers.isEmpty()){
            return error("已认证");
        }
        DjbDistrictUser add = new DjbDistrictUser();
        add.setUserId(user.getId());
        add.setDistrictId(districtId);
        DjbDistrict djbDistrict = districtMapper.selectDjbDistrictById(districtId);
        add.setDistrictName(djbDistrict.getName());
        add.setStatus(SYS_STATUS_TODO);
        add.setName(name);
        add.setMobile(mobile);
        add.setBuilding(building);
        DjbBuilding djbBuilding = buildingMapper.selectDjbBuildingById(building);
        String address="";
        if(djbDistrict.getType()==BUILDING_TYPE_BUILD){
            add.setUnit(unit);
            add.setFloor(floor);
            add.setRoom(room);
            add.setHead("");
            address=djbBuilding.getName()+(unit==0?"":unit+"单元")+floor+String.format("%02d",room);
        }else if(djbDistrict.getType()==BUILDING_TYPE_DEPARTMENT){
            address=djbBuilding.getName();
        }else if(djbDistrict.getType()==BUILDING_TYPE_COMPANY){
            address=djbBuilding.getName();
        }
        add.setAddress(address);
        add.setType(type);
        add.setAuthentication(1);
        districtUserMapper.insertDjbDistrictUser(add);
        if(djbDistrict.getType()==BUILDING_TYPE_BUILD&&building!=null&&floor!=null&&room!=null){
            //找管家
            String keeper = djbBuilding.getKeeper();
            if(!keeper.isEmpty()){
                JSONArray array = JSONArray.parseArray(keeper);
                boolean send=false;
                for(Object tmp : array){
                    JSONObject keep= (JSONObject)tmp;
                    String keep_id = keep.getString("id");
                    DjbAdmin admin = adminMapper.selectDjbAdminById(Integer.parseInt(keep_id));
                    /*解除审核状态和关注公众号的关联*/
//                    if(admin.getIsPost()==SYS_YES&&admin.getOpenId2() != null && !admin.getOpenId2().isEmpty()){
//                        sendExamNotice2(admin.getOpenId2(), name, mobile, address, add.getId());
//                    }
                    if(admin.getIsPost()==SYS_YES&&admin.getOpenId2() != null && !admin.getOpenId2().isEmpty()){
//                        sendExamNotice2(admin.getOpenId2(), name, "住户", address, add.getId());
                        sendExamNotice2(admin.getOpenId2(), name, mobile, address,type==1?"户主":"非户主", add.getId());
                        send=true;
                        break;
                    }
                }
                if(!send){
                    /*依次类推如果所有管家都不在岗 所有在岗服务主管都接收 如果所有服务主管都不在岗 不发送 */
                    DjbAdmin admin = new DjbAdmin();
                    admin.setDistrictId(districtId);
                    admin.setType(ADMIN_TYPE_MANAGER_WUYE);
                    List<DjbAdmin> djbAdmins = adminMapper.selectDjbAdminList(admin);
                    for(DjbAdmin tmp : djbAdmins){
                        if(tmp.getIsPost()==SYS_YES&&admin.getOpenId2() != null && !admin.getOpenId2().isEmpty()){
//                            sendExamNotice2(tmp.getOpenId2(), name, "住户", address, add.getId());
                            sendExamNotice2(tmp.getOpenId2(), name, mobile, address,type==1?"户主":"非户主", add.getId());
                        }
                    }
                }
            }
        }
        Map<String,Object> ret = new HashMap<>();
        return success(ret);
    }

    /*获取用户认证详情* */
    @GetMapping("/userVerifyDetail")
    @ResponseBody
    @UserLoginToken
    public AjaxResult userVerifyDetail(HttpServletRequest request,Integer id){
        DjbUser user = (DjbUser) request.getAttribute("user");
        DjbDistrictUser add = districtUserMapper.selectDjbDistrictUserById(id);
        if(add==null){
            return error("该认证已失效！");
        }
        Map<String,Object> ret = new HashMap<>();
        ret.put("detail",add);
        return success(ret);
    }

    /*小区住户、公司用户、部门用户认证认领* */
    @PutMapping("/VerifyClaim")
    @ResponseBody
    @UserLoginToken
    public AjaxResult VerifyClaim(HttpServletRequest request,Integer id,Integer type, Integer districtId,Integer building,Integer unit,Integer floor,Integer room, String mobile, String name){
        DjbUser user = (DjbUser) request.getAttribute("user");
        DjbDistrictUser add = districtUserMapper.selectDjbDistrictUserById(id);
        if(add==null){
            return error("该认证已失效！");
        }
        if(add.getAuthentication()==SYS_YES){
            return error("该认证已通过！");
        }
        DjbDistrictUser check = new DjbDistrictUser();
        check.setDistrictId(districtId);
        check.setUserId(user.getId());
        List<DjbDistrictUser> djbDistrictUsers = districtUserMapper.selectDjbDistrictUserList(check);
        if(!djbDistrictUsers.isEmpty()){
            return error("用户在该小区已认证！");
        }
        add.setUserId(user.getId());
        add.setDistrictId(districtId);
        DjbDistrict djbDistrict = districtMapper.selectDjbDistrictById(districtId);
        add.setDistrictName(djbDistrict.getName());
        add.setStatus(SYS_STATUS_PASS);
        add.setName(name);
        add.setMobile(mobile);
        add.setBuilding(building);
        DjbBuilding djbBuilding = buildingMapper.selectDjbBuildingById(building);
        String address="";
        if(djbDistrict.getType()==BUILDING_TYPE_BUILD){
            add.setUnit(unit);
            add.setFloor(floor);
            add.setRoom(room);
            add.setHead("");
            address=djbBuilding.getName()+(unit==0?"":unit+"单元")+floor+String.format("%02d",room);
        }else if(djbDistrict.getType()==BUILDING_TYPE_DEPARTMENT){
            address=djbBuilding.getName();
        }else if(djbDistrict.getType()==BUILDING_TYPE_COMPANY){
            address=djbBuilding.getName();
        }
        add.setAddress(address);
        add.setType(type);
        add.setAuthentication(1);
        districtUserMapper.updateDjbDistrictUser(add);
        Map<String,Object> ret = new HashMap<>();
        return success(ret);
    }

    /*住户认证删除* */
    @DeleteMapping("/Verifydelete")
    @ResponseBody
    @UserLoginToken
    public AjaxResult Verifydelete(HttpServletRequest request, Integer id){
        DjbUser user = (DjbUser) request.getAttribute("user");
        districtUserMapper.deleteDjbDistrictUserById(id);
        Map<String,Object> ret = new JSONObject();
        return success(ret);
    }

    /*获取用户信息* */
    @GetMapping("/getUserInfo")
    @ResponseBody
    @UserLoginToken
    public AjaxResult getUserInfo(HttpServletRequest request) throws Exception{
        DjbUser user = (DjbUser) request.getAttribute("user");
        Map<String,Object> ret = new JSONObject();
        ret.put("userInfo",user);
        return success(ret);
    }

    /*分享好友* */
    @GetMapping("/getShareId")
    @ResponseBody
    @UserLoginToken
    public AjaxResult getShareId(HttpServletRequest request) throws Exception{
        DjbUser user = (DjbUser) request.getAttribute("user");
        DjbShareInfo djbShareInfo = new DjbShareInfo();
        djbShareInfo.setUserId(user.getId());
        djbShareInfo.setCreateTime(DateUtils.getNowDate());
        shareInfoMapper.insertDjbShareInfo(djbShareInfo);
        Map<String,Object> ret = new JSONObject();
        ret.put("shareId",djbShareInfo.getId());
        return success(ret);
    }

    /*分享详情* */
    @GetMapping("/shareDetail")
    @ResponseBody
    @UserLoginToken
    public AjaxResult shareDetail(HttpServletRequest request,Integer id) throws Exception{
        DjbShareInfo djbShareInfo1 = shareInfoMapper.selectDjbShareInfoById(id);
        if(djbShareInfo1==null){
            return error("未查询到该分享");
        }
        Map<String,Object> ret = new JSONObject();
        ret.put("shareInfo",djbShareInfo1);
        ret.put("status",djbShareInfo1.getVisitId()==null?1:0);
        return success(ret);
    }

    /*登记列表 返回最近一次的登记* */
    @GetMapping("/registryList")
    @ResponseBody
    @UserLoginToken
    public AjaxResult registryList(HttpServletRequest request,Integer districtId, Integer gateId){
        DjbUser user = (DjbUser) request.getAttribute("user");
        DjbRegistry registry = new DjbRegistry();
        registry.setUserId(user.getId());
        registry.setDistrictId(districtId);
        if(gateId!=null){
            registry.setGateId(gateId);
        }
//        registry.setStatus(SYS_NO);
//        registry.setExamFlag("审核");
        registry.setCreateType(CREATE_TYPE_VISITOR);
        List<DjbRegistry> djbRegistries = registryMapper.selectDjbRegistryList(registry);
        if(djbRegistries.size()==0){
            return AjaxResult.warn("暂无登记历史列表");
        }
        Map<String,Object> ret = new HashMap<>();
        ret.put("registry",djbRegistries.get(0));
        return success(ret);
    }

    /*登记驳回列表* */
    @GetMapping("/rebutRegistryList")
    @ResponseBody
    @UserLoginToken
    public AjaxResult rebutRegistryList(HttpServletRequest request,Integer districtId){
        DjbUser user = (DjbUser) request.getAttribute("user");
        DjbRegistry registry = new DjbRegistry();
        registry.setUserId(user.getId());
        registry.setDistrictId(districtId);
        registry.setStatus(SYS_STATUS_REBUT);
        List<DjbRegistry> djbRegistries = registryMapper.selectDjbRegistryList(registry);
        if(djbRegistries.size()==0){
            return AjaxResult.warn("暂无登记驳回列表");
        }
        Map<String,Object> ret = new HashMap<>();
        ret.put("rebutRegistryList",djbRegistries);
        return success(ret);
    }

    /*登记修改* */
    @PutMapping("/registryUpdate")
    @ResponseBody
    @UserLoginToken
    @RepeatSubmit
    public AjaxResult registryUpdate(HttpServletRequest request,
                                     Integer registryId,String name,String mobile,String address,String reason,
                                     String type,Integer userType,Integer building,Integer unit,Integer floor,
                                     Integer room,String department,String remark,String idNumber,String visitPerson,Integer visitPersonId){
        DjbUser user = (DjbUser) request.getAttribute("user");
        Date nowDate = DateUtils.getNowDate();
        DjbRegistry registry = registryMapper.selectDjbRegistryById(registryId);
        if(registry==null){
            return error("登记不存在，请重新扫描");
        }
        if(registry.getStatus().equals(SYS_STATUS_PASS)){
            return error("该登记已放行");
        }
        DjbDistrict djbDistrict = districtMapper.selectDjbDistrictById(registry.getDistrictId());
        registry.setName(name);
        registry.setMobile(mobile);
        registry.setAddress(address);
        registry.setReason(reason);
        registry.setType(type);
        registry.setCreateName(user.getName());
        registry.setUserType(userType);
        registry.setCreateTime(nowDate);
        registry.setBuilding(building);
        registry.setVisitPerson(visitPerson);
        registry.setVisitPersonId(visitPersonId);
        if(djbDistrict.getType()==BUILDING_TYPE_BUILD){
            registry.setUnit(unit);
            registry.setFloor(floor);
            registry.setRoom(room);
        }else if(djbDistrict.getType()==BUILDING_TYPE_DEPARTMENT){

        }else if(djbDistrict.getType()==BUILDING_TYPE_COMPANY){

        }
        if(registry.getStatus().equals(SYS_STATUS_REBUT)){
            registry.setStatus(SYS_EXAM);
        }
        registryMapper.updateDjbRegistry(registry);

        if(department!=null && !department.isEmpty()){
            user.setLastDepartment(department);
        }
        if(remark!=null && !remark.isEmpty()){
            user.setLastRemark(remark);
        }
        if(idNumber!=null && !idNumber.isEmpty()){
            user.setIdNumber(idNumber);
        }
        /*业主登记的不需要记录*/
        if(!registry.getCreateType().equals(CREATE_TYPE_USER)){
            if(userType.equals(USER_TYPE_CAR)){
                user.setLastCar(name);
            }else{
                user.setLastName(name);
            }
            user.setLastPhone(mobile);
        }
        userMapper.updateDjbUser(user);
        Map<String,Object> ret = new HashMap<>();
        ret.put("status",registry.getStatus());
        return success(ret);
    }

    /*详情图片*/
    @GetMapping("/imageUrl/{id}")
    @PassToken
    public String imageUrl(HttpServletRequest request, Model model,  @PathVariable int id){
        DjbRelease release = releaseMapper.selectDjbReleaseById(id);
        if(release!=null&&!release.getImages().isEmpty()) {
            String images = release.getImages();
            String[] split = images.split(",");
            for(int i=0;i<split.length;i++){
                model.addAttribute("image"+i,split[i]);
            }
        }
        return "djb/imageUrl";
    }

    /*登记审核通过*/
    @GetMapping("/ExamRegistry/{id}/{userType}/{userId}")
    @PassToken
    public String ExamRegistry(HttpServletRequest request,@PathVariable int id,@PathVariable String userType,@PathVariable int userId){
        DjbRegistry registry = registryMapper.selectDjbRegistryById(id);
        if(registry==null){
            return "djb/examFail";
        }
        if(registry.getStatus().equals(SYS_STATUS_TODO)){
            return "djb/examSuccess";
        }
        String examName="";
        if(userType.equals("user")){
            DjbDistrictUser districtUser = new DjbDistrictUser();
            districtUser.setUserId(userId);
            List<DjbDistrictUser> djbDistrictUsers = districtUserMapper.selectDjbDistrictUserList(districtUser);
            if(!djbDistrictUsers.isEmpty()){
                examName=djbDistrictUsers.get(0).getName();
            }
        }else{
            DjbAdmin admin = adminMapper.selectDjbAdminById(userId);
            examName=admin.getName();
        }
        registry.setStatus(SYS_STATUS_TODO);
        registry.setExamFlag("审核");
        registry.setExamName(examName);
        registryMapper.updateDjbRegistry(registry);
        DjbUser djbUser;
        if(registry.getCreateType()==CREATE_TYPE_USER&&registry.getInputId()!=null){
            djbUser = userMapper.selectDjbUserById(registry.getInputId());
        }else{
            djbUser = userMapper.selectDjbUserById(registry.getUserId());
        }
        if(djbUser!=null&&djbUser.getOpenId2()!=null&&!djbUser.getOpenId2().isEmpty()){
            sendExamPassNotice(djbUser.getOpenId2(), registry.getName(), registry.getMobile(), registry.getAddress(), registry.getId(),registry.getType(),registry.getReason(),"user",djbUser.getId());
        }else{
            sendUserExamPass(djbUser.getOpenId(),registry.getName(), registry.getMobile(), registry.getAddress(),registry.getReason());
        }
        return "djb/examSuccess";
    }

    /*住户认证审核通过*/
    @GetMapping("/VerifyAddExam/{id}")
    @PassToken
    public String VerifyAddExam(HttpServletRequest request,@PathVariable int id){
        DjbDistrictUser districtUser = districtUserMapper.selectDjbDistrictUserById(id);
        if(districtUser==null){
            return "djb/examFail";
        }
        if(districtUser.getStatus()==SYS_STATUS_PASS){
            return "djb/examSuccess";
        }
        DjbDistrict djbDistrict = districtMapper.selectDjbDistrictById(districtUser.getDistrictId());
        String name="";
        //找业主
        DjbDistrictUser check = new DjbDistrictUser();
        check.setDistrictId(districtUser.getDistrictId());
        check.setBuilding(districtUser.getBuilding());
        if(djbDistrict.getType()==BUILDING_TYPE_BUILD){
            if(districtUser.getType()==1){
                name="户主";
            }else{
                name="非户主";
            }
        }else if(djbDistrict.getType()==BUILDING_TYPE_DEPARTMENT){
            if(districtUser.getType()==1){
                name="主管";
            }else{
                name="非主管";
            }
        }else if(djbDistrict.getType()==BUILDING_TYPE_COMPANY){
            if(districtUser.getType()==1){
                name="前台";
            }else{
                name="非前台";
            }
        }
        if(djbDistrict.getType()==BUILDING_TYPE_BUILD){
            check.setUnit(districtUser.getUnit());
            check.setFloor(districtUser.getFloor());
            check.setRoom(districtUser.getRoom());
        }
        List<DjbDistrictUser> djbDistrictUsers = districtUserMapper.selectDjbDistrictUserList(check);
        for(DjbDistrictUser tmp: djbDistrictUsers){
            if(tmp.getType().equals(0)) continue;
            DjbUser djbUser = userMapper.selectDjbUserById(tmp.getUserId());
            if(djbUser ==null) continue;
            /*消息改为关注公众号是模板消息，如果没有关注公众号直接用小程序订阅消息接受*/
            if(djbUser.getOpenId2()!=null&&!djbUser.getOpenId2().isEmpty()){
                /*关注了公众号*/
                sendExamNotice3(djbUser.getOpenId2(), districtUser.getName(),districtUser.getMobile(), name, districtUser.getAddress(), districtUser.getId(),"通过");
            }else {
                /*发送小程序订阅通知*/
                sendUserVerifyResult(djbUser.getOpenId(),districtUser.getName(),districtUser.getMobile(),districtUser.getAddress(),name);
            }
        }
        districtUser.setStatus(SYS_STATUS_PASS);
        districtUserMapper.updateDjbDistrictUser(districtUser);
        /*发送住户认证审核结果通知*/
        if(districtUser.getType()==0){
            DjbUser djbUser = userMapper.selectDjbUserById(districtUser.getUserId());
            if((djbUser.getOpenId2()!=null) && !djbUser.getOpenId2().isEmpty()){
                sendExamNotice3(djbUser.getOpenId2(), districtUser.getName(),districtUser.getMobile(), name, districtUser.getAddress(), districtUser.getId(),"通过");
            }else{
                /*发送小程序订阅通知*/
                sendUserVerifyResult(djbUser.getOpenId(),districtUser.getName(),districtUser.getMobile(),districtUser.getAddress(),name);
            }
        }
        return "djb/examSuccess";
    }

    /*跳转身份认证审核页面*/
    @GetMapping("/toVerifyAddExam/{id}")
    @PassToken
    public String VerifyAddExam(HttpServletRequest request, @PathVariable int id, ModelMap mmap){
        DjbDistrictUser districtUser = districtUserMapper.selectDjbDistrictUserById(id);
        if(districtUser==null){
            return "djb/examFail";
        }
        if(districtUser.getStatus()==SYS_STATUS_PASS){
            return "djb/examSuccess";
        }
        mmap.put("name",districtUser.getName());
        mmap.put("mobile",districtUser.getMobile());
        mmap.put("address",districtUser.getAddress());
        String name="";
        DjbDistrict djbDistrict = districtMapper.selectDjbDistrictById(districtUser.getDistrictId());
        if(djbDistrict.getType()==BUILDING_TYPE_BUILD){
            if(districtUser.getType()==1){
                name="户主";
            }else{
                name="非户主";
            }
        }else if(djbDistrict.getType()==BUILDING_TYPE_DEPARTMENT){
            if(districtUser.getType()==1){
                name="主管";
            }else{
                name="非主管";
            }
        }else if(djbDistrict.getType()==BUILDING_TYPE_COMPANY){
            if(districtUser.getType()==1){
                name="前台";
            }else{
                name="非前台";
            }
        }
        mmap.put("userType",name);
        return "djb/xmg_sfrz";
    }

    /*跳转访客登记审核页面*/
    @GetMapping("/toExamRegistry/{id}/{userType}/{userId}")
    @PassToken
    public String toExamRegistry(HttpServletRequest request,@PathVariable int id,@PathVariable String userType,@PathVariable int userId, ModelMap mmap){
        DjbRegistry registry = registryMapper.selectDjbRegistryById(id);
        if(registry==null){
            return "djb/examFail";
        }
        if(registry.getStatus().equals(SYS_STATUS_TODO)){
            return "djb/examSuccess";
        }
        mmap.put("name",registry.getName());
        mmap.put("mobile",registry.getMobile());
        mmap.put("address",registry.getAddress());
        mmap.put("reason",registry.getReason());
        mmap.put("department",registry.getDepartment());
        mmap.put("remark",registry.getRemark());
        mmap.put("type",registry.getType());
        mmap.put("regHis",registry.getRegHistoryNum());
        mmap.put("userType",userType);
        mmap.put("userId",userId);
        mmap.put("id",id);
        JSONObject tags=new JSONObject();
        DjbRelease release2 = new DjbRelease();
//            release2.setUserId(tmp.getUserId());
        if(registry.getUserType()==USER_TYPE_PERSON){
            release2.setMobile(registry.getMobile());
        }else{
            release2.setName(registry.getName());
        }
        release2.setUserType(registry.getUserType());
        List<DjbRelease> djbReleaseList1 = releaseMapper.selectHalfYearThreeTimeReleaseList(release2);
        for(DjbRelease tmp2: djbReleaseList1){
            if(!tmp2.getTag().isEmpty()){
                String tag1 = tmp2.getTag();
                tags.put(tag1,1);
            }
        }
        mmap.put("tags",tags.toJSONString());
        return "djb/xmg_registrationDetails";
    }

    /*新增订阅通知* */
    @PutMapping("/addRemind")
    @ResponseBody
    @UserLoginToken
    public AjaxResult addRemind(HttpServletRequest request,Integer registryId){
        DjbRegistry registry = registryMapper.selectDjbRegistryById(registryId);
        DjbUser user = (DjbUser) request.getAttribute("user");
        DjbUserRemind remind = new DjbUserRemind();
        remind.setUserId(user.getId());
        remind.setRegistryId(registryId);
        List<DjbUserRemind> djbUserReminds = remindMapper.selectDjbUserRemindList(remind);
        if(!djbUserReminds.isEmpty()){
            return success();
        }
        remind.setType(registry.getCreateType());
        remind.setState(0);//一次消息
        remind.setSend(0);//未发送
        if(registry.getCreateType()==CREATE_TYPE_USER){
            remind.setOpenId(user.getOpenId2());
        }else if(registry.getCreateType()==CREATE_TYPE_VISITOR){
            remind.setOpenId(user.getOpenId());
        }
        remind.setCreateTime(DateUtils.getNowDate());
        remindMapper.insertDjbUserRemind(remind);
        return success();
    }

    /*登记作废*/
    @PutMapping("/registryExpired")
    @ResponseBody
    @UserLoginToken
    public AjaxResult registryExpired(HttpServletRequest request,String registryIds){
        String[] split = registryIds.split(",");
        for(String tmp : split){
            DjbRegistry registry = registryMapper.selectDjbRegistryById(Integer.parseInt(tmp));
            registry.setStatus(SYS_STATUS_WASTE);
            registryMapper.updateDjbRegistry(registry);
        }
        return AjaxResult.success("成功");
    }

    /*登记删除*/
    @PutMapping("/registryDelete")
    @ResponseBody
    @UserLoginToken
    public AjaxResult registryDelete(HttpServletRequest request,Integer registryId){
        registryMapper.deleteDjbRegistryById(registryId);
        return AjaxResult.success("成功");
    }

    /*登记删除多个*/
    @PutMapping("/registryDeleteAll")
    @ResponseBody
    @UserLoginToken
    public AjaxResult registryDeleteAll(HttpServletRequest request,String registryIds){
        String[] split = registryIds.split(",");
        for(String id: split){
            registryMapper.deleteDjbRegistryById(Integer.parseInt(id));
        }
        return AjaxResult.success("成功");
    }

    /*通知户主*/
    @PutMapping("/sendUserExam")
    @ResponseBody
    @UserLoginToken
    public AjaxResult sendUserExam(HttpServletRequest request,Integer id){
        DjbRegistry registry = registryMapper.selectDjbRegistryById(id);
        //找业主
        DjbDistrictUser districtUser = new DjbDistrictUser();
        districtUser.setDistrictId(registry.getDistrictId());
        districtUser.setBuilding(registry.getBuilding());
        DjbDistrict djbDistrict = districtMapper.selectDjbDistrictById(registry.getDistrictId());
        if(djbDistrict.getType()==BUILDING_TYPE_BUILD){
            districtUser.setUnit(districtUser.getUnit());
            districtUser.setFloor(districtUser.getFloor());
            districtUser.setRoom(districtUser.getRoom());
        }
        List<DjbDistrictUser> djbDistrictUsers = districtUserMapper.selectDjbDistrictUserList(districtUser);
        for(DjbDistrictUser tmp: djbDistrictUsers){
            if(tmp.getType().equals(0)||tmp.getStatus()==SYS_STATUS_TODO) continue;
            DjbUser djbUser = userMapper.selectDjbUserById(tmp.getUserId());
            if(djbUser!=null&&djbUser.getOpenId2()!=null&&!djbUser.getOpenId2().isEmpty()){
                new Thread(() -> {
                    /*发送消息通知*/
                    sendExamNotice(djbUser.getOpenId2(), registry.getName(), registry.getMobile(),registry.getDistrictName()+ registry.getAddress(), registry.getId(),registry.getType(),registry.getReason(),"user",tmp.getId());
                }).start();
            }
        }
        return AjaxResult.success("成功");
    }

    /*登记详情*/
    @GetMapping("/registryDetail")
    @ResponseBody
    @UserLoginToken
    public AjaxResult registryDetail(HttpServletRequest request,int id) throws InterruptedException {
        DjbRegistry tmp = registryMapper.selectDjbRegistryById(id);
        DjbDistrict djbDistrict = districtMapper.selectDjbDistrictById(tmp.getDistrictId());
        DjbRelease release = new DjbRelease();
        if(tmp.getUserType()==USER_TYPE_PERSON){
            release.setMobile(tmp.getMobile());
        }else{
            release.setName(tmp.getName());
        }
        release.setDistrictId(tmp.getDistrictId());
        List<DjbRelease> djbReleaseList = releaseMapper.selectDjbReleaseList(release);
        tmp.setRegHistoryNum(djbReleaseList.size());
        JSONObject tags=new JSONObject();
        DjbRelease release2 = new DjbRelease();
//            release2.setUserId(tmp.getUserId());
        if(tmp.getUserType()==USER_TYPE_PERSON){
            release2.setMobile(tmp.getMobile());
        }else{
            release2.setName(tmp.getName());
        }
        release2.setUserType(tmp.getUserType());
        List<DjbRelease> djbReleaseList1 = releaseMapper.selectHalfYearThreeTimeReleaseList(release2);
        for(DjbRelease tmp2: djbReleaseList1){
            if(!tmp2.getTag().isEmpty()){
                String tag1 = tmp2.getTag();
                tags.put(tag1,1);
                break;
            }
        }
        tmp.setTags(tags);
        JSONObject ret =new JSONObject();
        ret.put("registry",tmp);
        ret.put("djbDistrict",djbDistrict);
        return AjaxResult.success("查询成功",ret);
    }

    /*事由列表*/
    @GetMapping("/reasonList")
    @ResponseBody
    @UserLoginToken
    public AjaxResult reasonList(HttpServletRequest request,Integer districtId){
        DjbUser user = (DjbUser) request.getAttribute("user");
        DjbReason reason = new DjbReason();
        reason.setDistrictId(districtId);
        reason.setIsOpen(1);
        List<DjbReason> djbReasons = reasonMapper.selectDjbReasonList(reason);
        if(djbReasons.isEmpty()){
            return AjaxResult.warn("无事由");
        }
        JSONObject ret = new JSONObject();
        ret.put("reasonList",djbReasons);
        return AjaxResult.success("查询成功",ret);
    }

    /*我的历史登记列表*/
    @GetMapping("/myRegistryList")
    @ResponseBody
    @UserLoginToken
    public AjaxResult myRegistryList(HttpServletRequest request){
        DjbUser user = (DjbUser) request.getAttribute("user");

        DjbRegistry registry = new DjbRegistry();
        registry.setUserId(user.getId());
        List<DjbRegistry> djbRegistries = registryMapper.selectDjbRegistryList(registry);
        if(djbRegistries.isEmpty()){
            return AjaxResult.warn("无历史登记");
        }
        JSONObject district = new JSONObject();
        JSONObject districtPhone = new JSONObject();
        JSONObject districtImg = new JSONObject();
        JSONObject gate = new JSONObject();
        for (DjbRegistry tmp : djbRegistries) {
//            if(tmp.getStatus()==SYS_STATUS_TODO) {
//                djbRegistries.remove(j);
//                j--;
//                continue;
//            }
//            String districtId = String.valueOf(tmp.getDistrictId());
//            if (district.containsKey(districtId)) {
//                tmp.setDistrictName(district.getString(districtId));
//            } else {
//                DjbDistrict djbDistrict = districtMapper.selectDjbDistrictById(tmp.getDistrictId());
//                if (djbDistrict == null) {
//                    tmp.setDistrictName("未知");
//                    district.put(districtId, "未知");
//                } else {
//                    tmp.setDistrictName(djbDistrict.getName());
//                    district.put(districtId, djbDistrict.getName());
//                }
//            }
//            if (districtPhone.containsKey(districtId)) {
//                tmp.setDistrictPhone(district.getString(districtId));
//            } else {
//                DjbDistrict djbDistrict = districtMapper.selectDjbDistrictById(tmp.getDistrictId());
//                if (djbDistrict == null) {
//                    tmp.setDistrictPhone("未知");
//                    districtPhone.put(districtId, "未知");
//                } else {
//                    tmp.setDistrictPhone(djbDistrict.getMobile());
//                    districtPhone.put(districtId, djbDistrict.getMobile());
//                }
//            }
//
//            if (districtImg.containsKey(districtId)) {
//                tmp.setDistrictImage(district.getString(districtId));
//            } else {
//                DjbDistrict djbDistrict = districtMapper.selectDjbDistrictById(tmp.getDistrictId());
//                if (djbDistrict == null) {
//                    tmp.setDistrictImage("");
//                    districtImg.put(districtId, "");
//                } else {
//                    tmp.setDistrictImage(djbDistrict.getCoverUrl());
//                    districtImg.put(districtId, djbDistrict.getCoverUrl());
//                }
//            }
//
//            String gateId = String.valueOf(tmp.getGateId());
//            if (gate.containsKey(gateId)) {
//                tmp.setGateName(gate.getString(gateId));
//            } else {
//                DjbGate gate1 = gateMapper.selectDjbGateById(tmp.getGateId());
//                if (gate1 == null) {
//                    tmp.setGateName("无");
//                    gate.put(gateId, "无");
//                } else {
//                    tmp.setGateName(gate1.getName());
//                    gate.put(gateId, gate1.getName());
//                }
//            }
        }
        JSONObject ret = new JSONObject();
        ret.put("myRegistryList",djbRegistries);
        return AjaxResult.success("查询成功",ret);
    }

    /*住户登记历史记录*/
    @GetMapping("/myUserRegistryList")
    @ResponseBody
    @UserLoginToken
    public AjaxResult myUserRegistryList(HttpServletRequest request,Integer districtId){
        DjbUser user = (DjbUser) request.getAttribute("user");
        DjbRegistry registry = new DjbRegistry();
        registry.setUserId(user.getId());
        registry.setCreateType(CREATE_TYPE_USER);
        registry.setDistrictId(districtId);
        List<DjbRegistry> djbRegistries = registryMapper.selectDjbRegistryList(registry);
        if(djbRegistries.isEmpty()){
            return AjaxResult.warn("无历史登记");
        }
        List<DjbRegistry> retu = new ArrayList<>();
        for (DjbRegistry tmp : djbRegistries) {
            if(retu.size()>=6) break;
            if(tmp.getStatus()==SYS_STATUS_PASS||tmp.getStatus()==SYS_STATUS_OUT) {
                retu.add(tmp);
            }
        }
        JSONObject ret = new JSONObject();
        ret.put("myUserRegistryList",retu);
        return AjaxResult.success("查询成功",ret);
    }

    /*我的审核列表*/
    @GetMapping("/myExamList")
    @ResponseBody
    @UserLoginToken
    public AjaxResult myExamList(HttpServletRequest request){
        DjbUser user = (DjbUser) request.getAttribute("user");
        DjbExam djbExam = new DjbExam();
        djbExam.setUserId(user.getId());
        djbExam.setDeleteFlag(0);
        List<DjbExam> djbExams = examMapper.selectDjbExamList(djbExam);
        if(djbExams.isEmpty()){
            return AjaxResult.warn("没有待审核的登记");
        }
        for(DjbExam tmp : djbExams){
            DjbRegistry registry1 = registryMapper.selectDjbRegistryById(tmp.getRegistryId());
            DjbDistrict djbDistrict = districtMapper.selectDjbDistrictById(registry1.getDistrictId());
            registry1.setDistrictType(djbDistrict.getType());
            tmp.setRegistry(registry1);
        }
        JSONObject ret = new JSONObject();
        ret.put("myExamList",djbExams);
        return AjaxResult.success("查询成功",ret);
    }

    /*小区认证住户列表*/
    @GetMapping("/districtUserList")
    @ResponseBody
    @UserLoginToken
    public AjaxResult myExamList(HttpServletRequest request,Integer districtId){
//        DjbUser user = (DjbUser) request.getAttribute("user");
        /*查询用户认证的小区*/
        DjbDistrictUser query = new DjbDistrictUser();
        query.setDistrictId(districtId);
        query.setStatus(SYS_YES);
        List<DjbDistrictUser> djbDistrictUsers = districtUserMapper.selectDjbDistrictUserList(query);
        JSONObject ret = new JSONObject();
        ret.put("districtUserList",djbDistrictUsers);
        return AjaxResult.success("查询成功",ret);
    }

    /*审核*/
    @PutMapping("/examRegistry")
    @ResponseBody
    @UserLoginToken
    public AjaxResult examRegistry(HttpServletRequest request,Integer examId){
        DjbUser user = (DjbUser) request.getAttribute("user");
        DjbExam djbExam = examMapper.selectDjbExamById(examId);
        if(djbExam==null){
            return AjaxResult.warn("examId错误");
        }
        DjbRegistry registry = registryMapper.selectDjbRegistryById(djbExam.getRegistryId());
        if(registry==null){
            return AjaxResult.warn("登记查询错误");
        }
        if(registry.getStatus().equals(SYS_STATUS_TODO)){
            return success("审核成功");
        }

        String examName="";
        if(djbExam.getExamType().equals("user")){
            DjbDistrictUser districtUser = new DjbDistrictUser();
            districtUser.setUserId(user.getId());
            List<DjbDistrictUser> djbDistrictUsers = districtUserMapper.selectDjbDistrictUserList(districtUser);
            if(!djbDistrictUsers.isEmpty()){
                examName=djbDistrictUsers.get(0).getName();
            }
        }else{
//            DjbAdmin admin = adminMapper.selectDjbAdminById(userId);
//            examName=admin.getName();
        }
        djbExam.setStatus(SYS_STATUS_PASS);
        examMapper.updateDjbExam(djbExam);
        registry.setStatus(SYS_STATUS_TODO);
        registry.setExamFlag("审核");
        registry.setExamName(examName);
        registryMapper.updateDjbRegistry(registry);
        DjbUser djbUser;
        if(registry.getCreateType()==CREATE_TYPE_USER&&registry.getInputId()!=null){
            djbUser = userMapper.selectDjbUserById(registry.getInputId());
        }else{
            djbUser = userMapper.selectDjbUserById(registry.getUserId());
        }
        if(djbUser!=null&&djbUser.getOpenId2()!=null&&!djbUser.getOpenId2().isEmpty()){
            sendExamPassNotice(djbUser.getOpenId2(), registry.getName(), registry.getMobile(), registry.getAddress(), registry.getId(),registry.getType(),registry.getReason(),"user",djbUser.getId());
        }else{
            sendUserExamPass(djbUser.getOpenId(),registry.getName(), registry.getMobile(), registry.getAddress(),registry.getReason());
        }
        DjbExam check = new DjbExam();
        check.setRegistryId(djbExam.getRegistryId());
        List<DjbExam> djbExams = examMapper.selectDjbExamList(check);
        for(DjbExam tmp : djbExams){
            tmp.setStatus(SYS_STATUS_PASS);
            examMapper.updateDjbExam(tmp);
        }
        return AjaxResult.success("审核成功");
    }

    /*忽略-删除*/
    @PutMapping("/deleteRegistry")
    @ResponseBody
    @UserLoginToken
    public AjaxResult deleteRegistry(HttpServletRequest request,Integer examId){
        DjbUser user = (DjbUser) request.getAttribute("user");
        DjbExam djbExam = examMapper.selectDjbExamById(examId);
        if(djbExam==null){
            return AjaxResult.warn("examId错误");
        }
//        DjbRegistry registry = registryMapper.selectDjbRegistryById(djbExam.getRegistryId());
//        if(registry==null){
//            return AjaxResult.warn("登记查询错误");
//        }
        djbExam.setDeleteFlag(1);
        examMapper.updateDjbExam(djbExam);
        DjbExam check = new DjbExam();
        check.setRegistryId(djbExam.getRegistryId());
        List<DjbExam> djbExams = examMapper.selectDjbExamList(check);
        for(DjbExam tmp : djbExams){
            tmp.setDeleteFlag(1);
            examMapper.updateDjbExam(tmp);
        }
        return AjaxResult.success("成功");
    }
}